/**
 * 跟平台sdk相关的都走此脚本
 */

import { IPlatform } from "./IPlatform";
import appplatform from "./PlatformProxy";


export class Platform {

    /**当前平台 */
    private _platType: number = 0;

    private _appId: string = "";

    private _sdk: IPlatform;

    constructor() {

        let sdkClass: new () => any = appplatform;

        let sdk: IPlatform = this._sdk = new Proxy(new sdkClass(), {

            get(target, name) {
                if (!target[name]) {
                    throw new Error("未实现" + name.toString() + "方法");
                }
                return target[name];
            },
            set(target, name, value) {
                throw new Error("禁止设置属性");
            },
            apply(target, thisArg, argArray) {
                if (target) {
                }

                return target.apply(thisArg, argArray);
            },
            construct(target, argArray) {
                throw new Error("禁止实例化");
            }

        })

        sdk.onShow(this.onshow.bind(this));
        sdk.onHide(this.onHide.bind(this));


        this._platType = sdk.platType;
        this._appId = sdk.appId;
    }

    login(): Promise<{ code: number, data: any }> {
        return this._sdk.login();
    }


    playAD(param: string) {
        return this.resolvePromise(this._sdk.showAd, param);
    }

    setItem(key: string, v: any) {
        if (Reflect.has(this._sdk, "setItem")) {
            this.setItem = (key: string, v: any) => this._sdk.setItem(key, v);

        } else {
            this.setItem = (key: string, v: any) => Laya.LocalStorage.setItem(key, v);
        }

        this.setItem(key, v);
    }

    getItem(key: string) {
        if (Reflect.has(this._sdk, "getItem")) {
            this.getItem = (key: string) => this._sdk.getItem(key);
        } else {
            this.getItem = (key: string) => Laya.LocalStorage.getItem(key);
        }

        return this.getItem(key);
    }

    deleteItem(key: string) {
        if (Reflect.has(this._sdk, "deleteItem")) {
            this.deleteItem = (key: string) => this._sdk.deleteItem(key);
        } else {
            this.deleteItem = (key: string) => Laya.LocalStorage.removeItem(key);
        }
        this.deleteItem(key);
    }

    /**
     * 切换前台
     * @param res 
     */
    onshow(res: any) {

    }

    /**
     * 切换后台
     * @param res 
     */
    onHide(res: any) {

    }

    get platType() {
        return this._platType;
    }

    // 账号唯一标识
    get appId() {
        return this._appId;
    }


    private resolvePromise<T>(p: (param?: any) => Promise<T>, param?: any): Promise<{ err: any, res: T }> {
        return new Promise((resolve, reject) => {
            p().then(res => {
                resolve({ err: null, res });
            }).catch(err => {
                resolve({ err, res: null });
            })
        })
    }
}

export const PLATFORM = new Platform();